package com.mvvmhabit.org.binding.viewadapter.webview

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.webkit.*
import androidx.annotation.RequiresApi
import androidx.databinding.BindingAdapter
import com.mvvmhabit.org.binding.command.BindingCommand
import java.lang.StringBuilder

@BindingAdapter(
    value = ["loadUrl", "onLoadWebViewFinish", "onLoadWebViewError", "onReceivedTitle", "shouldOverrideUrlLoading", "filePathValueCallback"],
    requireAll = false
)
fun loadUrl(
    webView: WebView, loadUrl: String, onLoadWebViewFinish: BindingCommand<Any>,
    onLoadWebViewError: BindingCommand<Any>,
    onReceivedTitle: BindingCommand<String>?,
    shouldOverrideUrlLoading: BindingCommand<WebResourceRequest>?,
    filePathValueCallback: BindingCommand<ValueCallback<Array<Uri?>?>?>?
) {
    webView.webViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            onLoadWebViewFinish.execute()
        }

        override fun onReceivedError(
            view: WebView?,
            request: WebResourceRequest?,
            error: WebResourceError?
        ) {
            super.onReceivedError(view, request, error)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                println("错误信息：：：" + error?.description.toString())
                println("错误信息：：：" + error?.errorCode)
            }
            onLoadWebViewError.execute()
        }

        override fun onReceivedHttpError(
            view: WebView?,
            request: WebResourceRequest?,
            errorResponse: WebResourceResponse?
        ) {
            super.onReceivedHttpError(view, request, errorResponse)
            onLoadWebViewError.execute()
        }

        override fun onReceivedSslError(
            view: WebView?,
            handler: SslErrorHandler?,
            error: SslError?
        ) {
            super.onReceivedSslError(view, handler, error)
            onLoadWebViewError.execute()
            handler?.proceed() // 忽略证书
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            if (request?.url?.path!!.startsWith("weixin://wap/pay?")) { // 支付重定向
                shouldOverrideUrlLoading?.execute(request)
                return true
            }
            webView.loadUrl(request.url?.path!!)
            return true
        }
    }

    webView.webChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            onReceivedTitle?.execute(title!!)
        }

        override fun onShowFileChooser(
            webView: WebView?,
            filePathCallback: ValueCallback<Array<Uri?>?>?,
            fileChooserParams: FileChooserParams?
        ): Boolean {
            filePathValueCallback?.execute(filePathCallback)
            return true
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        override fun onPermissionRequest(request: PermissionRequest) {
            request.grant(request.resources)
        }

    }
    webView.loadUrl(loadUrl)
    webViewSetting(webView)
}

@BindingAdapter(value = ["loadHtmlData"], requireAll = false)
fun loadHtmlData(webView: WebView, loadHtmlData: String?) {
/*    webView.loadDataWithBaseURL(
        "https://gank.io/api/v2",
        getHtmlDataContent(loadHtmlData), "text/html", "utf-8", null
    )*/
    if (!loadHtmlData.isNullOrEmpty()) {
        webView.loadData(getHtmlDataContent(loadHtmlData), "text/html", "utf-8")
    }
    webViewSetting(webView)
}

fun getHtmlDataContent(bodyHtml: String): String {
    val content = StringBuilder()
    content.append("<html><head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> <style>img{max-width: 100%; width:auto; height:auto!important;}</style></head>")
    content.append("<body>")
    content.append(bodyHtml)
    content.append("</body></html>")
    return content.toString()
}

@SuppressLint("SetJavaScriptEnabled")
fun webViewSetting(webView: WebView) {
    webView.settings.javaScriptEnabled = true //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
    webView.settings.allowFileAccess = true
    webView.settings.pluginState = WebSettings.PluginState.ON_DEMAND
    webView.settings.javaScriptCanOpenWindowsAutomatically = true
    webView.settings.loadsImagesAutomatically = true // 支持自动加载图片
    webView.settings.defaultTextEncodingName = "utf-8" // 设置编码格式
    webView.settings.setSupportZoom(false)
    webView.settings.builtInZoomControls = false
    webView.settings.useWideViewPort = true
    webView.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
    webView.settings.loadWithOverviewMode = true
    webView.settings.domStorageEnabled = true
    webView.settings.setGeolocationEnabled(true) // 设置开启定位功能
    webView.settings.setAppCacheEnabled(true) // /是否应用缓存
    webView.settings.databaseEnabled = true // 是否数据缓存
    webView.settings.domStorageEnabled = true // 是否节点缓存
    webView.settings.mediaPlaybackRequiresUserGesture = false
}
